from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
from contextlib import asynccontextmanager

from api import init_router
from conf.config import settings
from common.logger import logger
from common.redis import RedisManager
from common.postgres import postgres_lifespan
from common import register_docs, register_static_file
from middleware.cors import register_cors_middleware
from middleware.http_timing import register_http_timing_middleware


# Redis 管理器
redis_manager = RedisManager(settings.REDIS_URI)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理：使用推荐的上下文管理器方式管理连接池"""
    # 使用 PostgreSQL 生命周期管理器
    async with postgres_lifespan(
        db_uri=settings.DB_URI,
        init_start=settings.INIT_START,
        min_size=1,
        max_size=20
    ) as (pool, checkpointer, store):
        
        app.state.pool = pool
        app.state.checkpointer = checkpointer
        app.state.store = store

        # 初始化 Redis
        redis = await redis_manager.initialize()
        app.state.redis = redis

        logger.info("✅ Postgres checkpointer&store 和 Redis 初始化完成")
        
        try:
            yield
        finally:
            # ---- 关闭时 ----
            await redis_manager.close()
            logger.info("🛑 Redis 已关闭")


# FastAPI 实例
app = FastAPI(
    title="智能体API服务",
    description="智能体API服务，支持 LangGraph + Postgres + Redis",
    version=settings.VERSION,
    lifespan=lifespan,
)


# 添加根路径重定向
@app.get("/")
async def root():
    """根路径重定向到登录页面"""
    return RedirectResponse(url="/api/v1/test/login", status_code=302)

# 注册路由
init_router(app)

# 初始化静态文件
register_static_file(app)

# 使用本地docs静态文件
register_docs(app)

# 注册跨域中间件
register_cors_middleware(app)

# 注册http timing中间件
register_http_timing_middleware(app)


if __name__ == "__main__":
    import uvicorn

    logger.info("🚀 启动服务器中...")
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=5666,
        reload=True,
        log_level="info",
    )
